﻿using EntitiesGenerator.Dtos;
using EntitiesGenerator.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EntitiesGenerator
{
    public partial class PublishForm : Form
    {

        private string _solutionDir;
        private List<string> _allNupkgs;
        public PublishForm(string solutionDir)
        {
            InitializeComponent();
            _solutionDir = solutionDir;
        }

        #region events

        private void cbxAll_CheckedChanged(object sender, EventArgs e)
        {
            if (_allNupkgs == null)
                return;

            for (int i = 0; i < clsbNukgs.Items.Count; i++)
            {
                clsbNukgs.SetItemChecked(i, cbxAll.Checked);
            }
        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            BindNupkgs(textBox1.Text);
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                BindNupkgs(textBox1.Text);
        }

        private void PublishForm_Load(object sender, EventArgs e)
        {
            try
            {
                BindNupkgs();
                InitLastData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (_allNupkgs == null)
                return;

            for (int i = 0; i < clsbNukgs.Items.Count; i++)
            {
                clsbNukgs.SetItemChecked(i, !clsbNukgs.GetItemChecked(i));
            }
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                foreach (var item in clsbNukgs.CheckedItems)
                {
                    var nupkg = Path.Combine(_solutionDir, item.ToString());

                    if (File.Exists(nupkg))
                        File.Delete(nupkg);
                }

                BindNupkgs();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private async void btnPublish_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUrl.Text.IsNullOrWhiteSpace())
                {
                    MessageBox.Show("Nuget推送Url地址不能为空!");
                    return;
                }
                if (txtKey.Text.IsNullOrWhiteSpace())
                {
                    MessageBox.Show("Nuget推送Key不能为空!");
                    return;
                }
                //var nugetLocation = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "nuget.exe");

                //旧的nuget 命令行,需要启动nuget.exe,顾弃用
                //string command = nugetLocation + " push \"{0}\" " + txtKey.Text + " -Source " + txtUrl.Text;

                foreach (var item in clsbNukgs.CheckedItems)
                {
                    await Task.Run(async () =>
                     {
                         var nupkg = Path.Combine(_solutionDir, item.ToString());
                         string command = $"dotnet nuget push \"{nupkg}\" -k {txtKey.Text.Trim()} -s {txtUrl.Text.Trim()}";
                         string r = Cmd.Execute(command);
                         await ShowBuildMsg(r);
                     });
                }

                SaveLastData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region private method

        private void SaveLastData()
        {
            LastDataConfiguration.Instance.NugetUrl = txtUrl.Text;
            LastDataConfiguration.Instance.NugetKey = txtKey.Text;

            LastDataConfiguration.Instance.Save();
        }

        private void InitLastData()
        {
            if (!LastDataConfiguration.Instance.NugetUrl.IsNullOrWhiteSpace())
                txtUrl.Text = LastDataConfiguration.Instance.NugetUrl;
            if (!LastDataConfiguration.Instance.NugetKey.IsNullOrWhiteSpace())
                txtKey.Text = LastDataConfiguration.Instance.NugetKey;
        }

        private void BindNupkgs(string search = null)
        {
            _allNupkgs = Directory
                            .EnumerateFiles(_solutionDir, "*.nupkg", SearchOption.AllDirectories)
                            .Select(r => r.Substring(_solutionDir.Length + 1))
                            .Where(r => !r.StartsWith("packages"))
                            .ToList();

            clsbNukgs.Items.Clear();
            if (search.IsNullOrWhiteSpace())
                clsbNukgs.Items.AddRange(_allNupkgs.ToArray());
            else
                clsbNukgs.Items.AddRange(_allNupkgs.Where(r => Path.GetFileName(r).Contains(search.Trim())).ToArray());
        }

        //private Action<string> ShowBuildMsgAction =>
        //    (msg) =>
        //        {

        //            if (!txtMsg.Text.IsNullOrWhiteSpace())
        //                txtMsg.AppendText("\r\n");
        //            txtMsg.AppendText(msg);
        //            txtMsg.ScrollToCaret();
        //        };


        private async Task ShowBuildMsg(string msg)
        {
            await Task.Run(() =>
            {
                if (!txtMsg.Text.IsNullOrWhiteSpace())
                    txtMsg.AppendText("\r\n");
                txtMsg.AppendText(msg);
                txtMsg.ScrollToCaret();

            });
        }

        #endregion
    }
}
